package com.yuhj.cateyemovie.clients;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Comment;

import com.baidu.android.bbalbs.common.a.c;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.yuhj.cateyemovie.bean.Advertisement;
import com.yuhj.cateyemovie.bean.Comments;
import com.yuhj.cateyemovie.bean.Image;
import com.yuhj.cateyemovie.bean.MovieDetail;
import com.yuhj.cateyemovie.bean.PlayingMovieList;
import com.yuhj.cateyemovie.bean.User;
import com.yuhj.cateyemovie.interfaces.AdvertisementCallback;
import com.yuhj.cateyemovie.interfaces.ImageCallback;
import com.yuhj.cateyemovie.interfaces.MovieDetailCallback;
import com.yuhj.cateyemovie.interfaces.PlayingMovieCallback;
import com.yuhj.cateyemovie.interfaces.ShortsCommentsCallback;

import android.R.integer;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.widget.TextView;

/**
 * @name ClientApi
 * @Descripation 这是一个用来访问网络的类<br>
 *               1、<br>
 *               2、<br>
 *               3、<br>
 * @author 禹慧军
 * @date 2014-10-22
 * @version 1.0
 */
public class ClientApi {
	public ClientApi() {
		// TODO Auto-generated constructor stub
	}

	public static JSONObject ParseJson(final String path, final String encode) {
		// TODO Auto-generated method stub
		HttpClient httpClient = new DefaultHttpClient();
		HttpParams httpParams = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
		HttpConnectionParams.setSoTimeout(httpParams, 10000);
		HttpPost httpPost = new HttpPost(path);
		try {
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity(),
						encode);
				System.out.println("--->result:" + result);
				JSONObject jsonObject = new JSONObject(result);
				return jsonObject;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			return null;

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} finally {
			if (httpClient != null)
				httpClient.getConnectionManager().shutdown();
		}
		return null;

	}

	/**
	 * @param Url
	 *            正在上映的列表数据
	 * @return
	 * @return
	 */
	public static void getPlayingMovieData(String Url, final String catetory,
			final PlayingMovieCallback callback) {
		HttpUtils utils = new HttpUtils();
		// String
		// url="http://api.mobile.meituan.com/dianying/v4/movies.json?tp=hot&order=show_desc&ct=北京&utm_campaign=AmovieBmovieCD-1&movieBundleVersion=100&utm_source=jiuyao&utm_medium=android&utm_term=100&utm_content=865061021015330&ci=1&uuid=0C70BD71F236CD098446938FF0C001CC7F879E5BC046187CC4CA8C99BA0E39C7";

		utils.send(HttpMethod.GET, Url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				ArrayList<PlayingMovieList> list = null;
				list = new ArrayList<PlayingMovieList>();
				String result = responseInfo.result;
				try {
					JSONObject json = new JSONObject(result);
					JSONArray Data = json.getJSONArray(catetory);

					for (int i = 0; i < Data.length(); i++) {
						PlayingMovieList plaingMovieList = new PlayingMovieList();
						JSONObject data = Data.getJSONObject(i);
						plaingMovieList.setId(data.getInt("id"));
						plaingMovieList.setContent(data.getString("desc"));

						String imgString = data.getString("img");
						imgString = imgString.replace("w.h/", "");
						plaingMovieList.setImg(imgString);
						plaingMovieList.setLevel(data.getString("sc"));
						plaingMovieList.setWish(data.getLong("wish"));
						plaingMovieList.setName(data.getString("nm"));
						plaingMovieList.setNew(data.getBoolean("late"));
						plaingMovieList.setSummmary(data.getString("scm"));
						plaingMovieList.setTag(data.getString("ver"));
						list.add(plaingMovieList);
					}
					callback.getresult(list);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}

		});

	}

	/**
	 * @param Url
	 *            正在上映的列表数据
	 * @return
	 * @return
	 */
	public static void getAdvertisement(final AdvertisementCallback callback) {
		HttpUtils utils = new HttpUtils();
		String Url = "http://advert.mobile.meituan.com/api/v3/adverts?cityid=10&category=11&version=5.1&new=0&app=movie&clienttp=android&uuid=A1A230538BAA987DFF805E95D3B8D53E88E2B30EC7F1DF388DD8D99DFD2C3BF2&devid=352706060172190&uid=&movieid=&utm_campaign=AmovieBmovieC110189035512576D-1&movieBundleVersion=100&utm_source=wandoujia&utm_medium=android&utm_term=100&utm_content=352706060172190&ci=10&uuid=A1A230538BAA987DFF805E95D3B8D53E88E2B30EC7F1DF388DD8D99DFD2C3BF2";
		final ArrayList<Advertisement> list = new ArrayList<Advertisement>();
		utils.send(HttpMethod.GET, Url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String result = responseInfo.result;
				// System.out.println("-------result-<"+result);
				try {
					JSONObject json = new JSONObject(result);
					JSONArray Data = json.getJSONArray("data");
					// System.out.println("----Data->"+Data.toString());
					// System.out.println("----length-----"+Data.length());
					for (int i = 0; i < Data.length(); i++) {

						JSONObject element = Data.getJSONObject(i);
						// System.out.println("--------dgd--->>"+element.toString());
						Advertisement advertisement = new Advertisement();
						advertisement.setId(element.getInt("id"));
						advertisement.setImg(element.getString("imgUrl"));
						advertisement.setName(element.getString("name"));
						list.add(advertisement);
					}

					callback.getresult(list);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}

		});

	}

	/**
	 * @param Url
	 *            获取电影详情的信息
	 * @return
	 * @return
	 */
	public static void getMovieDetail(String Url,
			final MovieDetailCallback callback) {
		HttpUtils utils = new HttpUtils();
		final ArrayList<MovieDetail> list = new ArrayList<MovieDetail>();
		utils.send(HttpMethod.GET, Url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String result = responseInfo.result;
				try {
					JSONObject data = new JSONObject(result);
					MovieDetail movieDetail = new MovieDetail();
					movieDetail.setCat(data.getString("cat"));
					movieDetail.setCountry(data.getString("src"));
					movieDetail.setDirector(data.getString("dir"));
					movieDetail.setHowlongtime(data.getString("dur"));
					movieDetail.setId(data.getLong("id"));
					movieDetail.setLevel((float) data.getDouble("sc"));
					movieDetail.setName(data.getString("nm"));
					movieDetail.setsNum(data.getString("snum"));
					movieDetail.setStar(data.getString("star"));
					movieDetail.setSummarry(data.getString("dra"));
					movieDetail.setTime(data.getString("rt"));
					movieDetail.setVer(data.getString("ver"));
					movieDetail.setImg(data.getString("img")
							.replace("w.h/", ""));
					movieDetail.setPicCount(data.getInt("pn"));
					JSONArray imageArray = data.getJSONArray("photos");

					String[] images = new String[imageArray.length()];
					System.out.println("----image-" + images.length);
					for (int i = 0; i < imageArray.length(); i++) {
						// images[i].setImageUrl(imageArray.get(i).toString());
						String img = imageArray.getString(i);
						img = img.replace("w.h/", "");
						images[i] = img;
					}
					movieDetail.setImages(images);

					callback.getresult(movieDetail);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}

		});

	}

	/**
	 * @param Url
	 *            获取短评的信息
	 * @return
	 * @return
	 */
	public static void getShortComment(String Url,
			final ShortsCommentsCallback callback) {
		HttpUtils utils = new HttpUtils();
		final ArrayList<MovieDetail> list = new ArrayList<MovieDetail>();
		utils.send(HttpMethod.GET, Url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String result = responseInfo.result;
				try {
					ArrayList<Comments> list = new ArrayList<Comments>();
					JSONObject json = new JSONObject(result);
					JSONArray data = json.getJSONArray("cmts");
					for (int i = 0; i < data.length(); i++) {
						JSONObject element = data.getJSONObject(i);
						Comments comments = new Comments();
						comments.setApprove(element.getLong("approve"));
						comments.setComment(element.getString("content"));
						comments.setId(element.getLong("id"));
						comments.setReply(element.getLong("reply"));
						comments.setTime(element.getString("time"));
						User user = new User();
						user.setName(element.getString("nick"));
						user.setImage(element.getString("avatarurl"));
						user.setId(element.getString("userId"));
						comments.setUser(user);
						list.add(comments);
					}
					callback.getresult(list);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}

		});

	}

	/**
	 * @param Url
	 *            获取热门评论的信息
	 * @return
	 * @return
	 */
	public static void getHotComment(final String Url,
			final ShortsCommentsCallback callback) {
		System.out.println("-------Url->" + Url);
		HttpUtils utils = new HttpUtils();
		final ArrayList<MovieDetail> list = new ArrayList<MovieDetail>();
		utils.send(HttpMethod.GET, Url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String result = responseInfo.result;

				try {
					ArrayList<Comments> list = new ArrayList<Comments>();
					JSONObject json = new JSONObject(result);
					JSONArray data = json.getJSONArray("data");
					for (int i = 0; i < data.length(); i++) {
						JSONObject element = data.getJSONObject(i);
						Comments comments = new Comments();
						comments.setComment(element.getString("text"));
						comments.setTitle(element.getString("title"));
						comments.setId(element.getLong("id"));
						comments.setReply(element.getLong("commentCount"));
						comments.setTime(element.getLong("created")+"");
						JSONObject userJsonObject = element
								.getJSONObject("author");
						User user = new User();
						user.setName(userJsonObject.getString("username"));
						user.setImage(userJsonObject.getString("avatarurl"));
						user.setId(userJsonObject.getString("id"));
						comments.setUser(user);
						list.add(comments);
					}
					callback.getresult(list);

				} catch (Exception e) {
					// TODO: handle exception
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {
				System.out.println("----eror-->" + msg);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}

		});

	}
	
	/**
	 * @param Url
	 *            获取大图
	 * @return
	 * @return
	 */
	public static void getBigImage(final String Url,
			final ImageCallback callback) {
		HttpUtils utils = new HttpUtils();
		final ArrayList<MovieDetail> list = new ArrayList<MovieDetail>();
		utils.send(HttpMethod.GET, Url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String result = responseInfo.result;

				try {
					ArrayList<String> list = new ArrayList<String>();
					JSONObject json = new JSONObject(result);
					JSONArray data = json.getJSONArray("data");
					   for (int i = 0; i < data.length(); i++) {
						JSONObject element = data.getJSONObject(i);
					     list.add(element.getString("olink").replace("w.h/", ""));
					}
					callback.getresult(list);

				} catch (Exception e) {
					// TODO: handle exception
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {
				System.out.println("----eror-->" + msg);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}

		});

	}

	/**
	 * @param Url
	 *            获取大图
	 * @return
	 * @return
	 */
	public static void getSmallImage(final String Url,
			final ImageCallback callback) {
		HttpUtils utils = new HttpUtils();
		final ArrayList<MovieDetail> list = new ArrayList<MovieDetail>();
		utils.send(HttpMethod.GET, Url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String result = responseInfo.result;

				try {
					ArrayList<String> list = new ArrayList<String>();
					JSONObject json = new JSONObject(result);
					JSONArray data = json.getJSONArray("data");
					   for (int i = 0; i < data.length(); i++) {
						JSONObject element = data.getJSONObject(i);
					     list.add(element.getString("tlink").replace("w.h/", ""));
					}
					callback.getresult(list);

				} catch (Exception e) {
					// TODO: handle exception
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {
				System.out.println("----eror-->" + msg);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}

		});

	}


}
